package db.exchange.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import db.exchange.market.ExchangeEngine;
import db.exchange.message.Order;

public class Client {

	private static final Logger LOG = LogManager.getLogger(ExchangeEngine.class.getName());
	
	private ClientStatus status;
	private IClientController controller;
	private Transport transport ;	


	public ClientStatus getStatus() {
		return status;
	}

	public void setStatus(ClientStatus status, String message) {
		this.status = status;
		controller.updateStatus(status,message);
		switch (status) {
		case DISCONNECT:
			LOG.info("DISCONNECT");
			break;
		case CONNECT:
			LOG.info("CONNECT");
			break;
		case LOGIN:
			LOG.info("LOGIN");
			break;
		default:
			break;
		}
	}

	private HashMap<String, Order> orders = new HashMap<>();

	Client() {
		status = ClientStatus.DISCONNECT;
	}

	public HashMap<String, Order> getOrders() {
		return orders;
	}

	public void putNewOrder(Order order) {
		orders.put(order.getClientId(), order);
	}

	private int currentOrderIdNumber = 0;

	// static public MainWindow mainwindow;

	public String getNewOrderId() {
		currentOrderIdNumber++;
		return "Order"
				+ ((currentOrderIdNumber > 9) ? currentOrderIdNumber : "0"
						+ currentOrderIdNumber);
	}

	public Order getOrderById(String orderId) {
		return orders.get(orderId);
	}

	public void registerOrder(Order o) {
		orders.put(o.getOrderId(), o);
	}

	public void doConnect(String host, String port) {
		new Thread(transport).start();
	}

	public void newMessage(String message) {
		// message.

	}

	public String getClientsAsStringInversOrder() {
		StringBuilder row = new StringBuilder();
		ArrayList<String> keys = new ArrayList<String>(getOrders().keySet());
		Collections.sort(keys);
		Collections.reverse(keys);
		for (String key : keys) {
			row.append(orders.get(key));
			row.append("\n");
		}
		return row.toString();

	}

}
